function pretty_print() {	
    $(".markdown-body pre").addClass("prettyprint");
    $("#comment-list pre").addClass("prettyprint");
    prettyPrint();
}

pretty_print();

function readImageAndSend (item, ed) {
    var blob = item.getAsFile();
    var formData = new FormData();
    var name = encodeURIComponent('截图.png');
    formData.append('editormd-image-file', blob, name);
    $.ajax({
        url: '/app/laoha/attach/image',
        type: 'POST',
        data: formData,
		//这两个设置项必填
        contentType: false,
        processData: false,
        dataType: 'json',
        success: function (res) {
            if (res.success == 1) {
                var content = '![截图](' + res.data.url + ')';
                console.log(content);
                ed.insertValue(content);
            }
        }
    });
}

function editor(el) {
    if (!$('#'+el).length) return;
    var mobile = document.body.clientWidth < 600;
    var Editormd = editormd(el, {
        height: 300,
        placeholder: '',
        autoFocus: false,
        watch: false,
        path : "/app/laoha/vendor/editormd/lib/",  // Autoload modules mode, codemirror, marked... dependents libs path
        saveHTMLToTextarea : true,
        toolbarIcons : function() {
            return mobile ? ["undo", "bold", "quote", "list-ul", "list-ol", "hr", "image", "preview"] : ["bold", "del", "italic", "quote", "|", "list-ul", "list-ol", "hr", "|", "link", "image", "table", "code-block", "|", "watch"]
        },
        imageUpload    : true,
        imageFormats   : ["jpg", "jpeg", "gif", "png"],
        imageUploadURL : "/app/laoha/attach/image",
        onload: function () {
            var ed = this;
            $('#'+el)[0].addEventListener('paste', function (e) {
				// 添加到事件对象中的访问系统剪贴板的接口
                var clipboardData = e.clipboardData,
                    i = 0,
                    items, item, types;

                if (clipboardData) {
                    items = clipboardData.items;
                    if (!items) {
                        return;
                    }
                    item = items[0];
					 // 保存在剪贴板中的数据类型
                    types = clipboardData.types || [];
                    for (; i < types.length; i++) {
                        if (types[i] === 'Files') {
                            item = items[i];
                            break;
                        }
                    }
					// 判断是否为图片数据
                    if (item && item.kind === 'file' && item.type.match(/^image\//i)) {
                        readImageAndSend(item, ed);
                    }
                }
            });
        }
    });
    return Editormd;
}


comment_editor = editor('editor');


function comment_submit() {
    var content = $('#md-content').val();
    if (content=='') {
        return;
    }
	var root_id = $('#comment-list').data('root-id');
	var root = $('#comment-list').data('root');
	var status = $('#comment-list').data('status');
    $.ajax({
        url: '/app/laoha/api/comment/store',
        type: 'POST',
        data: { content: content, root_id: root_id,root: root,status:status},
        dataType: 'json',
        success: function (res) {
            if (res.code == 0) {
                var d = res.data;
				var status_str='';
				if(d.status!==0){
					status_str = '<p>【正在等待审核中......】</p>';
				}
                var comment = '\
				<div class="card shadow-sm my-3 p-3 rounded-0" data-comment-id="'+d.id+'">\
					<div class="row">\
						<div class="col-auto">\
							<img src="'+avatar+'" class="rounded-circle" alt="Avatar" width="50" height="50">\
                        </div>\
						<div class="col">\
							<div class="d-flex">\
								<div class="flex-grow-1">\
									<h6>'+nickname+'</h6>\
									<p class="text-muted">\
										<small>'+d.created_at+'</small>\
										<a class="pull-right text-muted" data-type="delete-comment" href="javascript:;">\
											<small>删除</small>\
										</a>\
										<a class="pull-right me-2 text-muted" data-type="edit-comment" href="javascript:;">\
											<small>编辑</small>\
										</a>\
									</p>\
								</div>\
							</div>\
							<div class="comment-content markdown-body">'+status_str+d.html+'</div>\
							<div class="reply-list border p-3 rounded">\
								<div class="no-reply text-center text-secondary"><small>暂无回复</small></div>\
							</div>\
                            <div class="input-group my-2">\
                                <textarea autoheight="true" class="form-control form-control-sm reply-textarea" rows="1" placeholder="撰写回复 ..." name="content"></textarea>\
                            </div>\
                            <div class="mt-y d-flex align-content-center justify-content-end">\
                                <button type="button" submit-type="reply" style="display: none" class="btn btn-primary btn-sm mt-1">\
                                    提交回复\
                                </button>\
                            </div>\
						</div>\
					</div>\
				</div>';
                $('#comment-list').append(comment);
                comment_editor.clear();
                $('#comments_count').html(parseInt($('#comments_count').html())+1);
                pretty_print();
                //$('div[data-comment-id="'+d.id+'"]')[0].scrollIntoView({behavior:'smooth', block:'end'});
                return;
            }
            alert(res.msg);
        }
    });
}

function delete_post(id) {
    if (!confirm('你确定要删除此文章吗？')) {
        return;
    }
    $.ajax({
        url: '/app/laoha/api/post/delete',
        type: 'POST',
        data: {id: id},
        dataType: 'json',
        success: function (res) {
            if (res.code == 0) {
                location = '/app/laoha/post';
                return;
            }
            alert(res.msg);
        }
    });
}



$(document).on('click', 'button[submit-type="reply"]', function (event) {
    var comment_id = $(event.currentTarget).parents('div[data-comment-id]').attr('data-comment-id');
	var root_id = $('#comment-list').data('root-id');
	var root = $('#comment-list').data('root');
	var status=$('#comment-list').data('status');
    if (!comment_id) return;
    var textarea = $('div[data-comment-id="'+comment_id+'"] .reply-textarea');
    var content = textarea.val();
    if (!content) return;
    var that = this;
    $.ajax({
        url: '/app/laoha/api/comment/store',
        type: 'POST',
        data: { content: content, parent_id: comment_id, root_id: root_id,root: root,status:status},
        dataType: 'json',
        success: function (res) {
            if (res.code == 0) {
                var d = res.data;
				var status_str='';
				if(d.status!==0){
					status_str = '<p>【正在等待审核中......】</p>';
				}
                var reply = '\
						<div data-reply-id="'+d.id+'">\
							<hr/>\
							<div class="d-flex align-items-center">\
								<div class="flex-shrink-0">\
									<img src="'+avatar+'" class="rounded-circle" alt="Avatar" width="30" height="30">\
								</div>\
								<div class="flex-grow-1 ps-3">'+nickname+'<small class="text-muted ms-3 fst-italic">'+d.created_at+'</small>\
									<a class="pull-right text-muted" data-type="delete-reply" href="javascript:;"> <small>删除</small></a>\
								</div>\
							</div>\
							<div class="reply-content markdown-body mt-1 ms-5">'+status_str+'<div class="fw-light">'+d.html+'</div></div>\
						</div>';
				$('div[data-comment-id="'+comment_id+'"] .no-reply').remove();
                $('div[data-comment-id="'+comment_id+'"] .reply-list').append(reply);
                textarea.val('');
                $(that).hide();
                pretty_print();
                return;
            }
            err(res.msg);
        }
    });
});

$(document).on('click', 'a[data-type="delete-comment"]', function (event) {
    var comment_id = $(event.currentTarget).parents('div[data-comment-id]').attr('data-comment-id');
    if (!comment_id) return;
    remove_comment(comment_id);
});

$(document).on('click', 'a[data-type="edit-comment"]', function (event) {
    var comment_id = $(event.currentTarget).parents('div[data-comment-id]').attr('data-comment-id');
    if (!comment_id) return;
    edit_comment(comment_id);
});

$(document).on('click', 'a[data-type="delete-reply"]', function (event) {
    var reply_id = $(event.currentTarget).parents('div[data-reply-id]').attr('data-reply-id');
    if (!reply_id) return;
    remove_reply(reply_id);
});

function remove_reply(id) {
    $.ajax({
        url: '/app/laoha/api/comment/delete',
        type: 'POST',
        data: {id: id},
        dataType: 'json',
        success: function (res) {
            if (res.code == 0) {
                $('div[data-reply-id="'+id+'"]').fadeOut(200, function () {
                    var parent = $(this).parent();
                    this.remove();
                    if (parent.children().length == 0) {
                        parent.append('');
                    }
                });
                return;
            }
            alert(res.msg);
        }
    });
}

function remove_comment(comment_id) {
    if (!confirm('你确定要删除此评论吗？')) return;
    $.ajax({
        url: '/app/laoha/api/comment/delete',
        type: 'POST',
        data: {id: comment_id},
        dataType: 'json',
        success: function (res) {
            if (res.code == 0) {
                $('div[data-comment-id="'+comment_id+'"]').fadeOut(200, function () {
                    this.remove();
                });
                var count = parseInt($('#comments_count').html())-1;
                $('#comments_count').html(count >= 0 ? count : 0);
                return;
            }
            alert(res.msg);
        }
    });
}

function edit_comment(id) {
    $('#re_edit_box_outer').fadeIn();
    $('#re_editor').remove();
    var content = '';
    $.ajax({
        url: '/app/laoha/api/comment/show?edit=1',
        type: 'GET',
        data: {id: id},
        dataType: 'json',
        success: function (res) {
            if (res.code == 0) {
                $('#re_edit_box').html('<div id="re_editor">\
                    <input type="hidden" name="id" value="'+id+'" id="edit_id">\
            <textarea style="display:none;" id="edit_content">'+res.data.content+'</textarea>\
            </div>');
                editor('re_editor');
                return;
            }
            alert(res.msg);
            $('#re_edit_box_outer').hide();
        }
    });
}

function edit_comment_save() {
    var id = $('#edit_id').val();
    var content = $('#edit_content').val();
    if (!id) {
        console.error('bad id');
        return;
    }
    if (content=='') {
        return;
    }
    $.ajax({
        url: '/app/laoha/api/comment/update',
        type: 'PUT',
        data: { content: content, id: id},
        dataType: 'json',
        success: function (res) {
            if (res.code == 0) {
                $('div[data-comment-id="'+id+'"] .comment-content').html(res.data.html);
                $('#re_edit_box_outer').hide();
                pretty_print();
                return;
            }
            alert(res.msg);
        }
    });

}

$(document).on('focus', '.reply-textarea', function (event) {
    var comment_id = $(this).parents('div[data-comment-id]').attr('data-comment-id');
    $('div[data-comment-id="'+comment_id+'"] button[submit-type="reply"]').show();
});

$(document).on('blur', '.reply-textarea', function (event) {
    if ($(this).val() !== '') return;
    var comment_id = $(this).parents('div[data-comment-id]').attr('data-comment-id');
    $('div[data-comment-id="'+comment_id+'"] button[submit-type="reply"]').hide();
});

$('#re_edit_box_outer .close').on('click', function () {
    $('#re_edit_box_outer').hide();
});



$(document).on('click', '.markdown-body img', function () {
    $('#background').remove();
    $(document.body).append('<div id="background" class="row align-items-center justify-content-center" style="position:fixed;top:0;left:0;right:0;bottom:0;background:rgba(26,26,26,.65) !important;z-index:10001"><div class="col-12 d-flex align-items-center justify-content-center"><img class="img-fluid" src="'+$(this).attr('src')+'"></div></div>');
});


$(document).on('click', '#background', function () {
    $('#background').remove();
});

//例 <a href="javascript:;" onclick="comment_check('/app/laoha/admin/post/check?status=0&id=<?=$data['id']?>','reload')">审核</a>
function comment_check(url,obj)
{
    var url = url;
    $.ajax({
        url: url,
        success: function (e) {
            if (e.code != 0) {
                err(e.msg);
                return;
            }
            alert('操作成功!');
			$('#'+obj).remove();			
			
        }
    });
}
